package com.qinghe.plant.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

public class ManageTool {

	private ManageTool() {
	}

	public static String GenerateRandomUid() {

		// 字符源，可以根据需要删减
		String generateSource = "0123456789abcdefghigklmnopqrstuvwxyz";
		String string = "";
		for (int i = 0; i < 20; i++) {
			// 循环随机获得当次字符，并移走选出的字符
			String nowStr = String
					.valueOf(generateSource.charAt((int) Math.floor(Math.random() * generateSource.length())));
			string += nowStr;
			generateSource = generateSource.replaceAll(nowStr, "");
		}
		return string;
	}

	public static String DateToString() {
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return simpleDateFormat.format(date);
	}
	

	public static String GetValue(Field field, Object obj) {
		try {

			// field.setAccessible(true);

			String name = field.getName();
			name = name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());// 将属性的首字母大写
			Method method = obj.getClass().getMethod(String.format("get%s", name));

			// 获取属性类型
			String type = field.getGenericType().toString();
			String value = null;
			switch (type) {
			case "class java.lang.String": {
				value = String.format("'%s'", (String) method.invoke(obj));// 调用getter方法获取属性值
			}
				break;
			case "class java.lang.Integer": {
				value = ((Integer) method.invoke(obj)).toString();
			}
				break;
			case "class java.lang.Double": {
				value = ((Double) method.invoke(obj)).toString();
			}
				break;
			case "class java.lang.Short": {
				value = ((Short) method.invoke(obj)).toString();
			}
				break;
			}
			return value;
		} catch (Exception e) {
			System.out.println(String.format("获取属性值错误：%s", e));
			return null;
		}

	}

	public static void SetValue(Field field, Object obj, String value) {
		try {
			field.setAccessible(true);
			String name = field.getName();

			// 将属性的首字母大写
			name = name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());

			// 获取属性类型
			String type = field.getGenericType().toString();
			Method method = null;
			switch (type) {
			case "class java.lang.String": {
				method = obj.getClass().getMethod("set" + name, String.class);
				method.invoke(obj, value);
			}
				break;
			case "class java.lang.Integer": {
				method = obj.getClass().getMethod("set" + name, Integer.class);
				method.invoke(obj, Integer.parseInt(value));
			}
				break;
			case "class java.lang.Double": {
				method = obj.getClass().getMethod("set" + name, Double.class);
				method.invoke(obj, Double.parseDouble(value));
			}
				break;
			case "class java.lang.Short": {
				method = obj.getClass().getMethod("set" + name, Short.class);
				method.invoke(obj, Short.parseShort(value));
			}
				break;
			}
		} catch (Exception e) {
			System.out.println(String.format("赋值错误:%s", e));
		}

	}

	public static void Log(Object message) {
		System.out.println(String.format("日志[%s]:%s", ManageTool.DateToString(), message));
	}

	public static String GenerateUUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	public static String GenerateUUID(int length) {
		UUID uid = UUID.randomUUID();
		long idx = uid.getLeastSignificantBits();
		StringBuilder buff = new StringBuilder();
		for (int i = 0; i < 12; i++) {
			buff.append(toa(0x1F & idx));
			idx >>>= 5;
		}
		long idxb = uid.getMostSignificantBits();
		buff.append(toa((idxb & 0x1) == 0 ? idx : idx + 0x10));
		idx = (idxb >>> 1);
		for (int i = 0; i < 13; i++) {
			buff.append(toa(0x1F & idx));
			idx >>>= 5;
		}
		return buff.reverse().toString().substring(0, length);
	}

	// 生成可见字符
	private static char toa(long lidx) {
		if (lidx < 10) {
			return (char) (0x30 + lidx);
		}
		lidx += (0x41 - 10);
		int[] skips = { 0x49, 0x4f, 0x57, 0x5a };
		for (int ch : skips) {
			if (lidx < ch) {
				break;
			}
			lidx++;
		}
		return (char) lidx;
	}

	// 获取包括基类的所有属性
	public static Field[] GetFields(Object object) {
		Field[] fields = object.getClass().getDeclaredFields();
		System.out.println(fields.length);

		Class<?> superclass = object.getClass().getSuperclass();
		Field[] superFields = superclass.getDeclaredFields();
		System.out.println(superFields.length);

		int length1 = fields.length;
		int length2 = superFields.length;

		fields = Arrays.copyOf(fields, length1 + length2);// 数组扩容
		System.arraycopy(superFields, 0, fields, length1, length2);
		System.out.println(Arrays.toString(fields));
		return fields;
	}

	// 插入新的模型信息
	public static <T> String GetAttributes(T obj) {
		Field[] fields = obj.getClass().getDeclaredFields();
		String attributes = "";
		for (int i = 0; i < fields.length; i++) {
			if (i == fields.length - 1) {
				attributes += String.format("%s=%s", fields[i].getName(), ManageTool.GetValue(fields[i], obj));
			} else {
				attributes += String.format("%s=%s,", fields[i].getName(), ManageTool.GetValue(fields[i], obj));
			}
		}
		return attributes;
	}

	public static <T> String[] GetFieldInfos(T obj) {
		Field[] fields = obj.getClass().getDeclaredFields();
		String attributes = "";
		String values = "";
		for (int i = 0; i < fields.length; i++) {
			if (i == fields.length - 1) {
				attributes += fields[i].getName();
				values += ManageTool.GetValue(fields[i], obj);
			} else {
				attributes += fields[i].getName() + ",";
				values += ManageTool.GetValue(fields[i], obj) + ",";
			}
		}
		return new String[] { attributes, values };
	}

	/*
	 * public static String GetCurrentTime() { SimpleDateFormat df = new
	 * SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式 return df.format(new
	 * Date()); }
	 */

	public static byte[] GetBytes(String filePath) {
		byte[] buffer = null;
		try {
			File file = new File(filePath);
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	public static String String2MD5(String inStr) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();

	}

	// 加密解密算法 执行一次加密，两次解密
	public static String ConvertMD5(String inStr) {

		char[] a = inStr.toCharArray();
		for (int i = 0; i < a.length; i++) {
			a[i] = (char) (a[i] ^ 't');
		}
		String s = new String(a);
		return s;
	}
}
